package com.cnn.beans;

import java.util.HashMap;
import java.util.Map;

/**
 * 工厂模式实现
 */
public class BeanFactory {
    
    private static Map<String, Object> cache = new HashMap<String, Object>();
    
    public static Fruit getInstance(String fruitName){
        Fruit f = null;
        try {
            f = (Fruit) Class.forName(fruitName).newInstance();
        }catch (Exception e){
            e.printStackTrace();
            }
        return f;
    }


    public static <T> T getBeanInstance(Class<T> classType) throws Exception {
        //通过传过来的Class类型对象，获取全类名，然后根据键获取值
		T t = (T)cache.get(classType.getName());
		//判断，如果返回的这个值不为空，整个方法返回值
        if(t != null){
            return t;
        }else {//如果为空，那就再根据全类名创建一个对象，再把这个对象放入map中，再返回这个对象
            t = (T)(Class.forName(classType.getName()).newInstance());
            cache.put(classType.getName(), t);
        }
        return t;
    }

    public static   Object create(){
        return null;
    }


    public static void main(String[] argvs) throws Exception {
        Apple s  = BeanFactory.getBeanInstance(Apple.class);
        System.out.println(s.hashCode());

        Apple s1  = BeanFactory.getBeanInstance(Apple.class);
        System.out.println(s1.hashCode());

        System.out.println(s == s1);
    }
    
}
